package jrain.fw.cfg.runtime;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jrain.fw.core.business.BusinessConst;
import jrain.fw.core.log.Logger;
import jrain.fw.core.log.LoggerFactory;
import jrain.fw.core.utils.FwUtils;
import jrain.utils.cls.ClassUtils;
import jrain.utils.collection.RDMap;
import jrain.utils.collection.RMap;
import jrain.utils.exception.ServiceException;
import jrain.utils.io.IoUtils;
import jrain.utils.lang.StringUtils;

/**
 * <pre>
 * 作者：489088214@qq.com 
 * 描述： 配置文件解析
 * </pre>
 */
public class CfgRuntimeSqlParser implements CfgRuntimeParser {

	public static Logger log = LoggerFactory.getLogger(CfgRuntimeSqlParser.class);

	public Map<String, RMap<String, Object>> parserCfg() {
		Map<String, Object> sqlMap = new HashMap<>();

		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		ClassUtils.getFiles("rsql", ".rsql").forEach(path -> {
			try {
				initFile(classLoader, path, sqlMap);
			} catch (Exception e) {
				String msg = "sql parser error,file={}";
				log.error(BusinessConst.LOG_BOOT_REQUEST, msg, e, path);
				throw new ServiceException(msg, e);
			}
		});
		log.info(BusinessConst.LOG_BOOT_REQUEST, "sql parser finish!,{}", this.getClass().getSimpleName());
		Map<String, RMap<String, Object>> rsMap = new HashMap<>();
		rsMap.put("sql", new RDMap<>(sqlMap));
		return rsMap;
	}

	@SuppressWarnings({ "unchecked" })
	private void initFile(ClassLoader classLoader, String path, Map<String, Object> rsMap) throws Exception {
		byte fileBytes[] = IoUtils.readStream(classLoader.getResourceAsStream(path));
		String json = new String(fileBytes, "UTF-8");
		log.debug(BusinessConst.LOG_BOOT_REQUEST, "sql file:{},json:{}", path, json);
		Map<String, Object> dataMap = FwUtils.getJsonService().toMap(json);
		if (dataMap != null) {
			String version = StringUtils.trimNull(dataMap.get("version"));
			if ("1.0".equals(version)) {
				List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("data");
				if (list != null) {
					for (Map<String, Object> sqlMap : list) {
						String busiKey = StringUtils.trimNull(sqlMap.get("busiKey"));
						String sqlCode = StringUtils.trimNull(sqlMap.get("sqlCode"));
						if (busiKey.length() > 0 && sqlCode.length() > 0) {
							String key = busiKey + "." + sqlCode;
							rsMap.put(key, sqlMap);
						}
					}
				}
			}
		}
	}

}
